package com.store.service.impl;

import com.store.entity.Cart;
import com.store.entity.Product;
import com.store.entity.SuperCart;
import com.store.mapper.CartMapper;
import com.store.mapper.ProductMapper;
import com.store.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.store.service.ex.AddCartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cai
 * @since 2022-07-14
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;

    @Override
    public Void addCart(int uid, Integer pid, Integer num, String username) {
        //Cart cart1= cartMapper.selectByUidAndPid(uid, pid);
        //封装对象
        Cart cart=new Cart();
        cart.setPid(pid);
        cart.setUid(uid);
        cart.setNum(num);
        cart.setPrice(productMapper.selectById(pid).getPrice());
        // 封装数据：4个日志
        LocalDateTime now=LocalDateTime.now();
        cart.setCreatedUser(username);
        cart.setCreatedTime(now);
        cart.setModifiedUser(username);
        cart.setModifiedTime(now);
        //加入购物车中
        int rows= cartMapper.insert(cart);
        if(rows!=1){
            throw new AddCartException("购物车添加失败");
        }
        return null;
    }

    @Override
    public List<SuperCart> getMyAllCart(Integer uid) {
        List<Cart> list= cartMapper.selectByUid(uid);
        List<SuperCart> data= new ArrayList<>();
        for (Cart cart:list){
            //ByPid查询商品
            Product product = productMapper.selectById(cart.getPid());
            //封装商品简单信息
            SuperCart superCart=new SuperCart();
            superCart.setCid(cart.getCid());
            superCart.setNum(cart.getNum());
            superCart.setPid(cart.getPid());
            superCart.setUid(cart.getUid());
            superCart.setPrice(cart.getPrice());
            superCart.setImage(product.getImage());
            superCart.setTitle(product.getTitle());
            data.add(superCart);
        }
        return data;
    }

    @Override
    public List<SuperCart> getSuperCartByCids(Integer uid, Integer[] cids) {
        List<SuperCart> list= cartMapper.selectSuperCart(cids);
        Iterator<SuperCart> it=list.iterator();
        while (it.hasNext()){
            SuperCart superCart=it.next();
            if( ! superCart.getUid().equals(uid)){
                //去除没有加入订单的部分
                list.remove(superCart);
            }
        }
        //返回加入订单的部分
        return list;
    }
}
